<template>
	<view class="p_bg_f3 p_b_128">
		<view class="confirm_main">
			<navigator url="/pages/my/address?order=true" hover-class="none" class="wrapper p_flex2">
				<view class="p_flex_1 p_flex2" v-if="!addressInfo.id">
					<image src="https://dy.sykj365.com/uploads/mini/dizhi1@2x.png" class="p_img_48 p_margin_r_16"></image>
					<view class="p_font_28 p_color_b2">选择收货地址</view>
				</view>
				<view class="p_flex_1" v-else>
					<view class="p_font_32 p_margin_b_8">
						{{addressInfo.province}}{{addressInfo.city}}{{addressInfo.area}}{{addressInfo.address}}
					</view>
					<view class="p_font_28 p_color_7a">{{addressInfo.name}}<text
							class="p_margin_l_16">{{(addressInfo.phone).replace(/(\d{3})\d{4}(\d{4})/, "$1****$2")}}</text>
					</view>
				</view>
				<image src="https://dy.sykj365.com/uploads/mini/youjiantou@2x.png" class="p_img_48 p_margin_l_48"></image>
			</navigator>
			<view class="wrapper">
				<orderContent :item="item" :classMargin="index != fileList.length - 1?'p_margin_b_48': ''"
					:priceNum="true" v-for="(item, index) in fileList" :key="index"></orderContent>
			</view>
			<view class="wrapper">
				<view class="p_font_24 p_color_7a p_margin_b_48">价格明细</view>
				<view class="p_flex9 p_margin_b_32">
					<view class="p_font_28">商品总价<text class="p_font_24 p_color_b2 p_margin_l_8">共{{num}}件商品</text>
					</view>
					<view class="p_font_28"><text class="p_font_20">¥</text>{{totalPrice}}</view>
				</view>
				<view class="p_font_24 p_color_b2 p_text_r p_margin_b_32">参与活动{{commission_price}}元,单面和70g彩色喷墨不参加活动
				</view>
				<view class="p_flex9 p_margin_b_32">
					<view class="p_font_28">运费</view>
					<view class="p_font_28"><text class="p_font_20">¥</text>{{wuliuPrice}}</view>
				</view>
				<view class="p_flex9 p_margin_b_32">
					<view class="p_font_28">分享抵扣金额</view>
					<view class="p_font_28"><text class="p_font_20">¥</text>{{shareDiscount}}</view>
				</view>
				<view class="p_flex9 p_margin_b_32">
					<view class="p_font_28">可用余额</view>
					<view class="p_flex2">
						<view class="p_font_28 p_color_ff5555"><text class="p_margin_r_8">-</text><text
								class="p_font_20">¥</text>{{payBalance}}</view>
						<image src="https://dy.sykj365.com/uploads/mini/xuanzhong@2x.png" class="p_img_48 p_margin_l_16"
							v-if="saleType == 0" @click="getBalanceChoose(0)"></image>
						<image src="https://dy.sykj365.com/uploads/mini/weixuanzhong@2x.png" class="p_img_48 p_margin_l_16" v-else
							@click="getBalanceChoose(1)"></image>
					</view>
				</view>
        <view v-if="taobaoTicket" class="p_flex9 p_margin_b_32">
        	<view class="p_font_28">淘宝优惠券</view>
        	<view class="p_flex2">
            <view class="tb-ticket-box">
              <view class="val" :class="{ disabled: couponInfo.id === 'taobao' }">{{couponInfo.id === 'taobao' ? '已选用' : '待使用'}}</view>
              <view class="price">{{taobaoTicket.deduction_price}}元</view>
            </view>
          </view>
        </view>
				<view class="p_flex9 p_margin_b_32" @click="getCol_('0')">
					<view class="p_font_28">优惠券</view>
					<view class="p_flex2">
						<view class="p_font_28 p_color_b2" v-if="!couponInfo.id || (couponInfo.ticketType == '1')">选择优惠券</view>
						<view class="p_font_28 p_color_ff5555" v-else>{{couponInfo.ticket_name}}</view>
						<!-- <view class="p_font_28 p_color_ff5555" v-else><text class="p_margin_r_8">-</text><text
								class="p_font_20">¥</text>{{couponInfo.deduction_price}}</view> -->
						<image src="https://dy.sykj365.com/uploads/mini/youjiantou@2x.png" class="p_img_48"></image>
						<image src="https://dy.sykj365.com/uploads/mini/xuanzhong@2x.png" class="p_img_48 p_margin_l_16"
							v-if="saleType == 1" @click.stop="getChooseCollet(0)"></image>
						<image src="https://dy.sykj365.com/uploads/mini/weixuanzhong@2x.png" class="p_img_48 p_margin_l_16" v-else
							@click.stop="getChooseCollet(1)">
						</image>
					</view>
				</view>
        <view class="p_flex9 p_margin_b_32" @click="getCol_('1')">
        	<view class="p_font_28">折扣券</view>
        	<view class="p_flex2">
        		<view class="p_font_28 p_color_b2" v-if="!couponInfo.id || (couponInfo.ticketType == '0')">选择折扣券</view>
        		<view class="p_font_28 p_color_ff5555" v-else>{{couponInfo.ticket_name}}</view>
        		<image src="https://dy.sykj365.com/uploads/mini/youjiantou@2x.png" class="p_img_48"></image>
        		<image src="https://dy.sykj365.com/uploads/mini/xuanzhong@2x.png" class="p_img_48 p_margin_l_16"
        			v-if="saleType == 2" @click.stop="getChooseCollet(0, '1')"></image>
        		<image src="https://dy.sykj365.com/uploads/mini/weixuanzhong@2x.png" class="p_img_48 p_margin_l_16" v-else
        			@click.stop="getChooseCollet(2, '1')">
        		</image>
        	</view>
        </view>
				<view class="p_flex10">
					<view class="p_font_24 p_color_7a p_margin_r_8">合计</view>
					<view class="p_font_32"><text class="p_font_24">¥</text>{{allP_ < 10?allP_: allPrice}}</view>
				</view>
				<view class="p_font_24 p_color_ff5555 p_text_r p_margin_t_16" v-if="allP_ < 10">不足10元按10元算</view>
			</view>
		</view>
		<bottomView :isShowPrice="true" :priceNum="allPrice" btnText1="去支付" :isShowNum="true" :number="num"
			@getSubmit="getSubmit">
		</bottomView>
		<!--  -->
		<van-popup :show="couponShow" position="bottom" round @click-overlay="couponShow = false">
			<view class="p_font_28 p_flex7 p_margin_tb_48">选择{{ticketType == '1' ? '折扣' : '优惠'}}券</view>
			<view class="p_flex8 p_margin_tb_80" v-if="collectList.length === 0">
				<image src="https://dy.sykj365.com/uploads/mini/zanwuyouhuiquan@2x.png" class="p_img_96 p_margin_b_32"></image>
				<view class="p_font_26 p_color_b2">暂无{{ticketType == '1' ? '折扣' : '优惠'}}券</view>
			</view>
			<view class="coupon_main" v-else>
				<ticket :item="item" v-for="item in collectList" :ticket-type="ticketType" @getC="getCChoose"></ticket>
			</view>
		</van-popup>
		<!-- 支付 -->
		<pay ref="payView" :order="true" :isShow="isPayShow" :priceNum="allPrice" @getClose="isPayShow = false;isPayBtn = true;" :isTaoBao="isTaoBao"
			@getChoosePay="getChoosePay"></pay>
		<!-- 首次支付弹窗 -->
		<tips :tipsShow="tipsShow" messages="新用户首单享受返余额优惠，返余额数值(最高16)=可参与活动金额-最低发货价10元，在订单完成后在小程序系统自动返还到余额。"
			confirmText="去支付" @getDialogConfirm="isPayShow = true;tipsShow = false;"></tips>
		<!-- 不可支付弹窗 -->
		<tips :tipsShow="tipsShow1" messages="当前所选文档打印配置超过三种请重新设置配置"
			confirmText="确定" @getDialogConfirm="tipsShow1 = false;"></tips>
	</view>
</template>

<script>
	import pay from './components/pay.vue';
	import tips from '../../components/tips.vue';
	import ticket from '../../components/ticket.vue';
	import bottomView from '../../components/bottomView.vue';
	import orderContent from '../../components/orderContent.vue';

	export default {
		components: {
			pay,
			tips,
			ticket,
			bottomView,
			orderContent
		},
		data() {
			return {
        taobaoTicket: null,
        ticketType: '0',
				ids: '',
				addressInfo: {},
				fileList: [],
				num: 0, // 商品数量 
				totalPrice: 0, // 商品总价
				wuliuPrice: 0, // 运费
				shareDiscount: 0, // 分享抵扣金额
				priceInfo: {},
				paperList: [],
				saleType: -1, // 0-余额 1-优惠券 2-折扣券
				salePrice: 0, // 优惠金额
				couponShow: false,
				couponInfo: {},
				allPrice: 0, // 文件价格 + 运费 -优惠金额
				allP_: 0, // 文件价格 + 运费
				collectList: [],
				isPayShow: false,
				isPayBtn: true,
				balance: 0,
				payBalance: 0,
				commission_price: 0,
				active_price: 0, // 参与活动的金额
				tipsShow: false,
				orderNum: 0,
				isBtn: true,
				isTaoBao: false,
				tipsShow1: false,
			}
		},
		onLoad(e) {
			this.ids = e.ids;
      this.getTaoBaoTicket();
			this.getDetail();
			this.getPaper();
			this.getPriceInfo();
			this.getUserBalance();
			this.getListData();
		},
		onShow() {
			if (uni.getStorageSync('getAddress')) {
				let a_ = uni.getStorageSync('getAddress');
				this.addressInfo = a_;
				this.getWuliuPrice(true);
				uni.removeStorageSync('getAddress');
			}
		},
		methods: {
			getDetail() {
				this.$http.post(this.$api.orderConfirm, {
					ids: this.ids
				}).then(res => {
					this.fileList = res.data.cart;
					this.num = res.data.num;
					this.totalPrice = res.data.total_price;
					this.commission_price = res.data.commission_price;
					this.shareDiscount = res.data.share_discount;
					let p_ = 0;
					this.fileList.forEach((n) => {
						if (n.commission == 1) {
							p_ += Number(n.price) * Number(n.num)
						}
					})
					this.active_price = p_.toFixed(2);

					if (res.data.address.id) {
						this.addressInfo = res.data.address;
						setTimeout(() => {
							this.getWuliuPrice(true);
						}, 500)
					}
				})
			},
			getPriceInfo() {
				this.$http.post(this.$api.price).then(res => {
					this.priceInfo = res.data;
				})
			},
			getPaper() {
				this.$http.post(this.$api.brand).then(res => {
					this.paperList = res.data;
				})
			},
			getWuliuPrice(e) {
				let a_ = this.priceInfo.area_json;
				let p1_ = 0; // 快递费
				let p2_ = 0; // 超出首重的费用
				let g_ = 0; // 总克数

				if (a_.length > 0) {
					a_.forEach((n) => {
						if (n.name === this.addressInfo.province || n.name + '省' === this.addressInfo.province) {
							p1_ = Number(this.priceInfo.first_weight_price);
						}
					})
				}

				this.fileList.forEach((n) => {
					this.paperList.forEach((m) => {
						if (n.brand == m.name) {
							// 重量(g) = 单张纸重量 * 纸张数 * 数量
							n.l_ = n.print_range.split('-');
							n.c_ = (Number(n.l_[1]) - Number(n.l_[0])) + 1;
							n.n_ = n.single_double == 1 ? Math.ceil(n.c_ / 2) : n.c_; // 单面 、双面
							n.r_ = Math.ceil(n.n_ / (n.reduce_num ? n.reduce_num : 1)); // 缩印						
							n.w_ = Number(m.weight) * n.r_ * Number(n.num);
							g_ += n.w_;
						}
					})
				})

				if (g_ > 1000 && p1_) { // 超出1kg加费用
					// 超出多少kg
					let kg_ = Math.ceil((g_ - 1000) / 1000);
					p2_ = kg_ * Number(this.priceInfo.continuation_weight_price);
				}

				this.wuliuPrice = p1_ + p2_;
				this.getAllPrice(e);
			},
			getAllPrice(e) {
				this.allP_ = (this.totalPrice + this.wuliuPrice).toFixed(2);

				if (e) {
					// 可用余额
					if (this.commission_price == 0) {
						this.payBalance = Number(this.balance).toFixed(2);
					} else {
						if (Number(this.balance) <= (this.totalPrice - 10) || (this.totalPrice - 10) <= 0) {
							this.payBalance = Number(this.balance).toFixed(2);
						} else if (Number(this.balance) > (this.totalPrice - 10) && (this.totalPrice - 10) > 0) {
							this.payBalance = (this.totalPrice - 10).toFixed(2);
						}
					}

					if (this.saleType == 0) {
						this.salePrice = this.payBalance;
					}
				}

				if (this.totalPrice <= 10) {
					this.allPrice = (10 + this.wuliuPrice).toFixed(2);
					this.saleType = -1;
					this.couponInfo = {};
					this.salePrice = 0;
				} else {
					
					this.allPrice = (this.allP_ - this.salePrice).toFixed(2);
				}
			},
			// 优惠券
			getCol_(t = '0') {
				if (!this.addressInfo.id) return getApp().getMsg('请选择收货地址');
				if (this.commission_price == 0) return getApp().getMsg('该订单不满足返佣，优惠券不可用');
				if (Number(this.totalPrice) <= 10) return getApp().getMsg('当前订单总价不大于10，优惠券不可用');
        this.ticketType = t;
				this.couponShow = true;
        this.getCollect();
			},
			getCollect() {
        this.collectList = [];
				this.$http.post(this.$api.userTicket, {
					type: 0,
          ticket_type: this.ticketType
				}).then(res => {
					this.collectList = res.data;
          if (this.ticketType == '0') {
            this.getTaoBaoTicket(1);
          }
				})
			},
			getTaoBaoTicket(f = 0) {
				this.$http.post(this.$api.isTaobao, {}).then(res => {
					if (res.code == 20000) {
						const t = {
							id:'taobao', // 淘宝好评返现特殊id
							ticket_name: '淘宝好评返现优惠券',
							limitation_price: '10',
							deduction_price: res.data,
							status: '0',
              ticketType: '0'
						}
            if (f === 0) {
              this.taobaoTicket = t;
            } else {
              this.collectList.unshift(t);
            }
					}
				})
			},
			getCChoose(item) {
				if (this.active_price < Number(item.limitation_price)) return getApp().getMsg('当前优惠券不可用');
				this.couponInfo = item;
				this.couponShow = false;				
			},
			getChooseCollet(i, t = '0') {
				if (!this.addressInfo.id) return getApp().getMsg('请选择收货地址');
				if (this.commission_price == 0) return getApp().getMsg('该订单不满足返佣，优惠券不可用');
				if (Number(this.totalPrice) <= 10) return getApp().getMsg('当前订单总价不大于10，优惠券不可用');
				if (i == 0) {
					this.saleType = -1;
					this.salePrice = 0;
				} else {
					if (!this.couponInfo.id) {
            this.ticketType = t;
						this.couponShow = true;
            this.getCollect();
						return
					}
					this.saleType = i;
					this.salePrice = this.couponInfo.id !=='taobao' ? Number(this.couponInfo.deduction_price) : 0; // 淘宝好评返现优惠券，不直接优惠，好评后返现
				}
				this.getAllPrice();
			},
			// 余额
			getUserBalance() {
				this.$http.post(this.$api.userinfo).then(res => {
					this.balance = Number(res.data.balance);
				})
			},
			getBalanceChoose(i) {
				if (!this.addressInfo.id) return getApp().getMsg('请选择收货地址');
				if (i == 0) {
					this.saleType = -1;
					this.salePrice = 0;
				} else if (i == 1) {
					if (!this.payBalance) {
						getApp().getMsg('暂无余额可用');
						return
					}

					if (this.commission_price == 0) {
						getApp().getMsg('该订单不满足返佣，余额不可用');
						return
					}

					if (this.totalPrice <= 10) {
						getApp().getMsg('当前订单总价不大于10，余额不可用');
						return
					}
					this.saleType = 0;
					this.salePrice = this.payBalance;
				}
				this.getAllPrice();
			},
			// 我的订单
			getListData() {
				this.$http.post(this.$api.orderList, {
					page: 1,
					type: 0
				}).then(res => {
					this.orderNum = res.data.data.length;
				})
			},
			// 去支付
			getSubmit() {
				const typeList = this.fileList.reduce((preValue,value) => {
						console.log(JSON.stringify(preValue.map(i => i.brand)))
						if(preValue.length == 0) {
							return [value]
						}
						if(!preValue.some(i => i.brand == value.brand && i.colour == value.colour)) {
							return [...preValue,value]
						}
						return preValue
				}, [])
				console.log(typeList)
				if(typeList.length >= 3) {
					this.tipsShow1 = true;
					return;
				}
				if (!this.addressInfo.id) return getApp().getMsg('请选择收货地址');
				if (this.addressInfo.province == '新疆维吾尔自治区' || this.addressInfo.province == '西藏自治区') return getApp()
					.getMsg('新疆/西藏地区不可选');
				if (Number(this.totalPrice) <= 10) {
					if (this.saleType == 1 || this.saleType == 2) {
						return getApp().getMsg(`当前订单总价不大于10，${this.saleType == 1 ? '优惠' : '折扣'}券不可用`);
					} else if (this.saleType == 0) {
						return getApp().getMsg('当前订单总价不大于10，余额不可用');
					}
				}

				// if (this.orderNum == 0) {
				// 	this.tipsShow = true;
				// } else {
				// 	if(this.isPayBtn) {
				// 		this.isPayShow = true;
				// 		this.isPayBtn = false;
				// 	}					
				// }
				if(this.isPayBtn) {
					this.isPayShow = true;
					this.isPayBtn = false;
				}
				if(this.couponInfo.id == 'taobao'){
					this.isTaoBao = true;
				}
			},
			getChoosePay(e) {
				let form_ = {
					ids: this.ids,
					address_id: this.addressInfo.id,
					user_ticket_id: this.saleType == 1 || this.saleType == 2 ? this.couponInfo.id : 0,
					balance: this.saleType == 0 ? this.payBalance : 0, // 余额
					pay_type: e,
					freight: this.wuliuPrice,
					is_taobao: this.isTaoBao ? 1 : 0,
				}

				this.isPayShow = false;
				
				if(!this.isBtn) return
				
				this.isBtn = false;
				
				this.$http.post(this.$api.orderAdd, form_).then(res => {					
					if (e == 0) {
						this.$refs.payView.wxPay(res.data);
					}

					if (e == 1) {
						let phone = this.addressInfo.phone;
						uni.redirectTo({
							url: '/pages/index/taobaoPay?orderNumber=' + res.data
						});
						this.isPayShow = false;
						uni.setStorageSync('set', true);
					}

					if (e == 2) {
						let phone = this.addressInfo.phone;
						uni.redirectTo({
							url: '/pages/index/pddPay?orderNumber=' + res.data
						});
						this.isPayShow = false;
						uni.setStorageSync('set', true);
					}
					
					setTimeout(() => {
						this.isBtn = true;
					}, 500)
				})
			}
		}
	}
</script>

<style lang="less">
  .tb-ticket-box {
    border-radius: 3px;
    height: 48rpx;
    line-height: 48rpx;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    .val {
      background-color: rgba(red, .1);
      color: red;
      padding: 0 18rpx;
      &.disabled {
        background-color: #f0f0f0;
        color: #666;
      }
    }
    .price {
      color: #fff;
      background-color: red;
      padding: 0 18rpx;
    }
  }
	.confirm_main {
		padding: 32rpx;
		box-sizing: border-box;
		min-height: calc(100vh - 128rpx);
	}

	.wrapper {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		margin-bottom: 32rpx;

		&:last-child {
			margin-bottom: 0;
		}
	}

	.coupon_main {
		background-color: #F3F3F3;
		overflow-y: auto;
		max-height: 500rpx;
	}

	.ticket_list {
		margin: 20rpx auto;
	}
</style>